# -*- coding: utf-8 -*-
from openerp.osv import osv, fields

class view_stock_exchange_wizard(osv.osv_memory):
    """销售和采购退换货共用一个 产品行表"""
    _name = "view.stock.exchange.wizard"
    _columns = {
        'begin_date': fields.date(u'开始时间'),
        'end_date': fields.date(u'结束时间'),
        'product_id': fields.many2one('product.product', u'产品'),
        'product_message': fields.html(u'产品信息')
    }

    def onchange_product_id(self, cr, uid, ids, begin_date, end_date, product_id_input, context=None):
        """根据 根据时间段和产品名称搜出
            这段时间内包含这个产品的套装组合数量
            数据先组装成这种形式 { '[(产品id, 产品名称)]': {
                    'in':{'产品id'： 产品数量},
                    'out': {'产品id'： 产品数量}
                }
            }
            然后用这个dict 生成 <table></table> 表格
        """
        change_obj = self.pool.get('stock.change')
        move_obj = self.pool.get('stock.move')
        domain = [('state', '=', 'done')]
        if begin_date:
            domain.append(('change_date', '>=', begin_date))
        else:
            begin_date = u'很久之前'
        if end_date:
            domain.append(('change_date', '<', end_date))
        else:
            end_date = u'现在'
        if product_id_input:
            domain.extend(['|', ('move_in_lines.product_id', '=', product_id_input),
                           ('move_out_lines.product_id', '=', product_id_input)])
        else:
            return {}
        all_product_dict = {}
        for change_dict in change_obj.search_read(cr, uid, domain, ['move_in_lines', 'move_out_lines'], context=context):
            if len(change_dict.get('move_in_lines', [])) != 1 and len(change_dict.get('move_out_lines', [])) != 1:
                continue
            current_product_in, current_product_out = {}, {}
            product_ids = []
            for move_dict in move_obj.search_read(cr, uid,
                                                  [('id', 'in', change_dict.get('move_in_lines', []) + change_dict.get(
                                                      'move_out_lines', []))], ['product_id', 'product_uom_qty'], context=context):
                product_ids.append(move_dict.get('product_id', [False])[1])
                if move_dict.get('id') in change_dict.get('move_in_lines', []):
                    current_product_in.update({move_dict.get('product_id'): move_dict.get('product_uom_qty')})
                if move_dict.get('id') in change_dict.get('move_out_lines', []):
                    current_product_out.update({move_dict.get('product_id'): move_dict.get('product_uom_qty')})
            str_product_ids = str(sorted(product_ids))
            all_product_dict.setdefault(str_product_ids, {'in': {}, 'out': {}})
            if len(change_dict.get('move_in_lines', [])) == 1:
                product_in = all_product_dict.get(str_product_ids).get('in')
                for product_id, product_qty in current_product_in.iteritems():
                    product_in.update({product_id: product_in.get(product_id, 0) + product_qty}) \
                        if product_id in product_in else product_in.update({product_id: product_qty})
            else:
                product_out = all_product_dict.get(str_product_ids).get('out')
                for product_id, product_qty in current_product_in.iteritems():
                    product_out.update({product_id: product_out.get(product_id, 0) + product_qty * -1}) \
                        if product_id in product_out else product_out.update({product_id: product_qty * -1})

            if len(change_dict.get('move_out_lines', [])) > 1 or len(change_dict.get('move_in_lines', [])) == 1:
                product_out = all_product_dict.get(str_product_ids).get('out')
                for product_id, product_qty in current_product_out.iteritems():
                    product_out.update({product_id: product_out.get(product_id, 0) + product_qty}) \
                        if product_id in product_out else product_out.update({product_id: product_qty})
            else:
                product_in = all_product_dict.get(str_product_ids).get('in')
                for product_id, product_qty in current_product_out.iteritems():
                    product_in.update({product_id: product_in.get(product_id, 0) + product_qty * -1}) \
                        if product_id in product_out else product_in.update({product_id: product_qty* -1})
        html_list = []
        html_list.append('<table border="1" cellspacing="0" width="100%" height="100%">')
        product_dict= self.pool.get('product.product').search_read(cr, uid, [('id', '=', product_id_input)],
                                                                    ['name', 'default_code'], context=context)[0]
        html_list.append('<caption> %s - %s 产品 [%s]%s 组合</caption>' % \
                         (begin_date, end_date, product_dict.get('default_code'), product_dict.get('name')))
        html_list.append('<tr><th>入库套装</th> <th>套装数量</th><th>出库子件</th> <th>子件数量</th></tr>')
        for product_str, value in all_product_dict.iteritems():
            html_list.append("<tr>")
            html_list.append("<td >")
            rowspan = str(len(value.get('out').keys()) // len(value.get('in').keys()))
            for product_val, qty in value.get('in').iteritems():
                html_list.append("<tr>")
                if rowspan != '0':
                    html_list.append("<td rowspan='%s'>%s</td>"
                                     "<td rowspan='%s'>%s</td>" % (rowspan, product_val[1], rowspan,  qty))
                else:
                    html_list.append("<td>%s</td>"
                                     "<td>%s</td>" % (product_val[1], qty))
            multi_row = True
            for product_val, qty in value.get('out').iteritems():
                html_list.append("<tr>") if not multi_row else ''
                multi_row = False
                html_list.append(
                    "<td>%s</td>"
                    "<td>%s</td>" % (product_val[1], qty))
                html_list.append("</tr>")
            html_list.append("</td>")
            html_list.append("</tr>")
        html_list.append("</table>")
        return {'value': {'product_message': ''.join(html_list)}}


